﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
using Bzure.Common.Core;


namespace Bzure.Mvc.Controllers
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public class MvcControllerFilter : FilterAttribute, IActionFilter
    {
        public const string BzureControllerKey = "_bzure_controller_flag_2012";
        public string Flag { get; private set; }
        public MvcControllerFilter(string flag)
        {
            this.Flag = flag;
        }
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (ApplicationStartContextMvcControllerExtensions.ActionFilterBuilder.IsNotNull())
            {
                IActionFilter filter = ApplicationStartContextMvcControllerExtensions.ActionFilterBuilder();
                filter.OnActionExecuted(filterContext);
            }
        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.HttpContext.Items[BzureControllerKey] = this.Flag;
            if (ApplicationStartContextMvcControllerExtensions.ActionFilterBuilder.IsNotNull())
            {
                IActionFilter filter = ApplicationStartContextMvcControllerExtensions.ActionFilterBuilder();
                filter.OnActionExecuting(filterContext);
            }
        }
    }

    public static class BzureControllerExtensions
    {
        public static bool IsBzureController(this HttpContextBase context)
        {
            return context.Items.Contains(MvcControllerFilter.BzureControllerKey);
        }
        public static bool IsBzureController(this HttpContext context)
        {
            return context.Items.Contains(MvcControllerFilter.BzureControllerKey);
        }
        public static void ClearBzureFlag(this FiltedController controller)
        {
            if (controller.HttpContext.Items.Contains(MvcControllerFilter.BzureControllerKey))
                controller.HttpContext.Items.Remove(MvcControllerFilter.BzureControllerKey);
        }
    }
}
